/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.members.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.BatchCardRecord;
import com.qinyeit.serviceapp.entity.Member;
import com.qinyeit.serviceapp.entity.MemberCard;
import com.qinyeit.serviceapp.entity.enums.MemberCardState;
import com.qinyeit.serviceapp.entity.enums.PeriodType;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.repository.members.MemberCardRepository;
import com.qinyeit.serviceapp.service.members.BatchCardRecordService;
import com.qinyeit.serviceapp.service.members.MemberCardService;
import com.qinyeit.serviceapp.utils.CompuUtils;
import com.qinyeit.serviceapp.utils.Lang;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyetech.springstage.core.date.DateField;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.service.BaseService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.regex.Pattern;

/** 
 * ClassName: MemberCardServiceImpl <br/> 
 * Function: 会员卡 业务实现 <br/> 
 * date: 2018-12-04 11:15:51 <br/> 
 * 
 * @author liuwenjin
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class MemberCardServiceImpl extends BaseService<MemberCard, Long> implements MemberCardService {


	@Autowired
	private MemberCardRepository memberCardRepository;
	@Autowired
	private BatchCardRecordService batchCardRecordService;

	private final Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");

	@Override
	public void saveBatchCard(BatchCardRecord record) {
		if (StringUtils.isBlank(record.getStartNo())){
			throw new BusinessRunTimeException("其实编号不能为空",10002);
		}
		if (record.getCount()==null || record.getCount()<=0){
			throw new BusinessRunTimeException("制卡数量不能为0",10003);
		}
		if(!pattern.matcher(record.getStartNo()).matches()){
			throw new BusinessRunTimeException("起始编号必须为数字",10001);
		}
		if(CompuUtils.compareTo(record.getCount(),0)<=0){
			throw new BusinessRunTimeException("制卡数量必须大于0",10002);
		}
		int len = 0;
		String lastNo = "";
		List<Integer> st = null;
		if (StringUtils.isNotBlank(record.getExclude())){
			st = JSON.parseArray(record.getExclude(), Integer.class);
		}

		MemberCard memberCard = null;
		List<MemberCard> memberCardList = Lists.newArrayList();
		do{
			if (StringUtils.isBlank(lastNo)){
				lastNo = record.getCardPre()+record.getStartNo();
			}else {
				lastNo = Lang.getNextNo(lastNo);
			}
			log.info("下一个编号 ： ---------- "+lastNo);
				if(CollectionUtils.isNotEmpty(st)){
				boolean boo = false;
				for (Integer integer : st) {
					if(lastNo.endsWith(integer.toString())){
						boo=true;
						break;
					}
				}
				if (boo){
					continue;
				}
			}
			memberCard = new MemberCard();
			memberCard.setNo(lastNo);
			memberCard.setBatchId(record.getId());
			memberCard.setDeposit(record.getDeposit());
			memberCard.setType(record.getCardType());
			memberCard.setStartTime(DateUtils.date());
			memberCard.setMerchantGroupId(record.getMerchantGroupId());
			memberCard.setMakeCardType(record.getMakeCardType());
			if(record.getPeriod()== PeriodType.LONGTERM){
				memberCard.setEndTime(DateUtils.offsiteDate(DateUtils.date(), DateField.YEAR,100));
			}else if(record.getPeriod()==PeriodType.FIVEYEARS){
				memberCard.setEndTime(DateUtils.offsiteDate(DateUtils.date(), DateField.YEAR,5));
			}else /*if(record.getPeriod()==PeriodType.TENYEARS){
				memberCard.setEndTime(DateUtils.offsiteDate(DateUtils.date(), DateField.YEAR,10));
			}else*/ if(record.getPeriod()==PeriodType.THREEYEARS){
				memberCard.setEndTime(DateUtils.offsiteDate(DateUtils.date(), DateField.YEAR,3));
			}else if (record.getPeriod()==PeriodType.TWOYEARS){
				memberCard.setEndTime(DateUtils.offsiteDate(DateUtils.date(), DateField.YEAR,2));
			}else if(record.getPeriod()==PeriodType.ONEYEAR){
				memberCard.setEndTime(DateUtils.offsiteDate(DateUtils.date(), DateField.YEAR,1));
			}
			memberCardList.add(memberCard);
			len++;
		}while (len<record.getCount());

		memberCardRepository.saveAll(memberCardList);
		record.setNo(record.getCardPre()+record.getStartNo()+"-"+lastNo);
		batchCardRecordService.update(record);
	}

	@Override
	public Boolean verifyRepeat(String cardPre, String startNo, Integer count, String exclude,Long merchantGroupId) {
		if(!pattern.matcher(startNo).matches()){
			throw new BusinessRunTimeException("起始编号必须为数字",10001);
		}
		if(CompuUtils.compareTo(count,0)<=0){
			throw new BusinessRunTimeException("制卡数量必须大于0",10002);
		}
		int len = 0;
		String lastNo = "";
		List<Integer> st = JSON.parseArray(exclude, Integer.class);
		boolean exist = false;
		Searchable searchable = null;
		do{
			if (StringUtils.isBlank(lastNo)){
				lastNo = cardPre+startNo;
			}else {
				lastNo = Lang.getNextNo(lastNo);
			}
			if(CollectionUtils.isNotEmpty(st)){
				boolean boo = false;
				for (Integer integer : st) {
					if(lastNo.endsWith(integer.toString())){
						boo=true;
						break;
					}
				}
				if (boo){
					continue;
				}
			}
			searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
			searchable.addSearchParam("no_eq",lastNo);
			exist = this.exists(searchable);
			log.info("----------  重复结果 ：{}",exist);
			if(exist){
				break;
			}

			len++;
		}while (len<count);

		log.info("----------  res ：{}",exist);
		return exist;
	}

	@Override
	public MemberCard bindVip(Member member, Long merchantGroupId, QyMap cardData,MemberCard memberCard) {


		if (member!=null){
			memberCard.setVipId(member.getId());
		}
		log.info("会员id --- ： {}",cardData.getLong("vip_id"));
		if (cardData.getLong("vip_id")==-1){
			//vip_id 不存在
			memberCard.setVipId(null);
		}

		log.info("会员卡密码 ： {}",cardData.getString("password"));
		memberCard.setUuid(cardData.getString("uuid"));
		memberCard.setEndTime(cardData.getTime("end_time"));
		memberCard.setStartTime(cardData.getTime("start_time"));
		memberCard.setState(MemberCardState.valueOf(cardData.getString("state")));
		memberCard.setDeposit(cardData.getDouble("deposit"));
		memberCard.setAmount(cardData.getDouble("amount"));
		memberCard.setGiftAmount(cardData.getDouble("gift_amount"));
		memberCard.setGiftPoint(cardData.getDouble("gift_point"));
		memberCard.setPassword(cardData.getString("password"));
		memberCard.setPoint(cardData.getDouble("point"));
		memberCard.setTotalAmount(cardData.getDouble("total_amount"));
		memberCard.setTotalGiftAmount(cardData.getDouble("total_gift_amount"));
		memberCard.setTotalPoint(cardData.getDouble("total_point"));
		memberCard = this.update(memberCard);
		return memberCard;
	}
}